import { CredentialMeta } from "~/denokv/resume.ts";
import { useComputed, useSignal } from "@preact/signals";
import STDTable from "~/components/stdtable.tsx";
import { DriveMeta } from "~/denokv/resume.ts";
import { useRef } from "preact/hooks";
import { Fragment } from "preact/jsx-runtime";

interface ResumeTableProps {
  action: string;
  data: CredentialMeta[];
}
export default ({ data }: ResumeTableProps) => {
  const choosedSet = useSignal(new Set<number | string>());

  function handleCopy(params: string | number) {
    const newUrl = new URL(location.href);
    newUrl.pathname = "/resume";
    newUrl.searchParams.set("st", params.toString());
    const type = "text/plain";
    const blob = new Blob([newUrl.toString()], { type });
    const data = [new ClipboardItem({ [type]: blob })];
    navigator.clipboard?.write(data).then(() => {
      alert("已复制");
    });
  }

  /**
   * 删除处理逻辑
   */
  const commiting = useSignal(false);
  const disabled = useComputed(() => {
    return !choosedSet.value.size || commiting.value;
  });

  /**
   * 查看访问设备
   */
  const dialogRef = useRef<HTMLDialogElement>(null);
  const choosedDrive = useSignal<Partial<CredentialMeta>>({});

  function showDetail(row: CredentialMeta) {
    dialogRef.current?.show();
    choosedDrive.value = row;
  }
  return (
    <Fragment>
      <dialog
        ref={dialogRef}
        class="fixed  rounded-lg z-40 max-h-screen p-4 overflow-y-auto transition-transform  bg-white w-max dark:bg-gray-800"
        aria-labelledby="drawer-label"
      >
        <h5
          id="drawer-label"
          class="inline-flex items-center mb-4 text-base font-semibold text-gray-500 dark:text-gray-400"
        >
          <svg
            class="w-4 h-4 me-2.5"
            aria-hidden="true"
            xmlns="http://www.w3.org/2000/svg"
            fill="currentColor"
            viewBox="0 0 20 20"
          >
            <path d="M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z" />
          </svg>设备信息
        </h5>
        <button
          aria-controls="drawer-example"
          onClick={() => {
            dialogRef.current?.close();
          }}
          class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 absolute top-2.5 end-2.5 flex items-center justify-center dark:hover:bg-gray-600 dark:hover:text-white"
        >
          <svg
            class="w-3 h-3"
            aria-hidden="true"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 14 14"
          >
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"
            />
          </svg>
          <span class="sr-only">Close menu</span>
        </button>

        <STDTable<DriveMeta>
          tableList={choosedDrive.value?.drives}
          columns={[
            {
              header: "创建时间",
              key: "createAt",
              render: (r) => {
                return new Date(r.createAt).toLocaleString();
              },
            },
            {
              header: "设备id",
              key: "driveId",
            },
            {
              header: "留言条数",
              render: (r) => {
                return r.messages?.length
                  ? (
                    <a
                      class="font-medium text-blue-600 dark:text-blue-500 hover:underline"
                      href={`/admin/message?di=${r.driveId}`}
                    >
                      查看({r.messages?.length})
                    </a>
                  )
                  : 0;
              },
            },
          ]}
        >
        </STDTable>
      </dialog>

      <STDTable<CredentialMeta>
        class="h-full"
        onSelect={(rows) => {
          choosedSet.value = new Set(rows?.map((d) => d.id));
        }}
        tableList={data}
        actions={[
          <button
            name={"action"}
            value={"active"}
            className="w-full px-4 rounded py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white"
          >
            激活
          </button>,
          <button className="w-full px-4 rounded py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">
            禁用
          </button>,
          <button
            disabled={disabled}
            className="w-full px-4 rounded py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white"
          >
            删除分享
          </button>,
          <a
            href="/admin/resume/edit"
            className="w-full inline-block px-4 rounded py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white"
          >
            新增分享
          </a>,
        ]}
        columns={[
          {
            selectionType: "checkbox",
            key: "id",
          },
          {
            header: "创建时间",
            key: "createAt",
          },
          {
            header: "分享目标",
            key: "corporateName",
          },
          {
            header: "有效期",
            key: "duration",
          },
          {
            header: "state",
            key: "id",
          },
          {
            header: "有效期单位",
            key: "durationUnit",
          },
          {
            header: "已查看设备",
            key: "drives",
            render: (r) => (
              <a
                onClick={() => {
                  // e.preventDefault();
                  // e.stopPropagation();
                  showDetail(r);
                }}
                class="font-medium text-blue-600 dark:text-blue-500 hover:underline cursor-pointer"
              >
                查看{`(${r.drives?.length ?? 0})`}
              </a>
            ),
          },
          {
            header: "分享",
            type: "action",
            render: (r) => {
              return (
                <a
                  class="hover:cursor-pointer text-blue-600"
                  onClick={() => {
                    handleCopy(r.id);
                  }}
                >
                  复制
                </a>
              );
            },
          },
        ]}
      >
      </STDTable>
    </Fragment>
  );
};
